package com.itheima.service;

import com.itheima.dao.TxLogDao;
import com.itheima.domain.Order;
import com.itheima.domain.TxLog;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author MI
 * @ClassName OrderServiceImpl4Listener.java
 * @createTime 2021年11月24日 23:19:00
 */
@Service
@RocketMQTransactionListener(txProducerGroup = "tx_producer_group")
public class OrderServiceImpl4Listener implements RocketMQLocalTransactionListener {
    @Resource
    OrderServiceImpl4 orderServiceImpl4;

    //执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        try {
            String txId = msg.getHeaders().get("txId").toString();
            Order order = (Order) arg;
            orderServiceImpl4.createOrder(txId, order);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Resource
    private TxLogDao txLogDao;

    //消息回查
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        String txId = msg.getHeaders().get("txId").toString();
        Optional<TxLog> byId = txLogDao.findById(txId);
        if (byId.isPresent()) {
            //本地事物成功
            return RocketMQLocalTransactionState.COMMIT;
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
